﻿using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using SM2;

namespace SM23
{
    public static class SM2Encryption
    {
        public static String Encrypt( string data_string)
        {
            string publicKeyHex = "0484C7466D950E120E5ECE5DD85D0C90EAA85081A3A2BD7C57AE6DC822EFCCBD66620C67B0103FC8DD280E36C3B282977B722AAEC3C56518EDCEBAFB72C5A05312";
            string privateKey = "8EDB615B1D48B8BE188FC0F18EC08A41DF50EA731FA28BF409E6552809E3A111";
            // 如果是130位公钥，.NET使用的话，把开头的04截取掉
            if (publicKeyHex.Length == 130)
            {
                publicKeyHex = publicKeyHex.Substring(2, 128);
            }
            // 公钥X，前64位
            string x = publicKeyHex.Substring(0, 64);
            // 公钥Y，后64位
            string y = publicKeyHex.Substring(64);
            // 获取公钥对象
            AsymmetricKeyParameter publicKey1 = GM.GetPublickeyFromXY(new BigInteger(x, 16), new BigInteger(y, 16));
            // Sm2Encrypt: C1C3C2
            // Sm2EncryptOld: C1C2C3
            byte[] digestByte = GM.Sm2Encrypt(Encoding.UTF8.GetBytes(data_string), publicKey1);
            string strSM2 = Hex.ToHexString(digestByte);
            return strSM2;
        }
    }
}
